package com.taotao.common.fastdfs;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import javax.swing.border.StrokeBorder;

import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.FileInfo;
import org.csource.fastdfs.StorageClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.kischang.fastdfs.FastDFSTemplateFactory;
import com.github.kischang.fastdfs.pool.ConnectionPoolFactory;
import com.taotao.config.CommonConfig;
import com.taotao.function.Function;

/**
 * fastDFS帮助类
 * 
 * @author QYJ
 *
 */
@Service
public class FastDfsHelper {

	/**
	 * 客户端配置文件
	 */
	private String client_config;

	/**
	 * fdfscleint连接池工厂
	 */
	@Autowired
	ConnectionPoolFactory factory;

	/**
	 * 
	 * @param client_config
	 *            配置文件名
	 * @param fdfsFactoryTemp
	 *            fdfs工厂模板
	 * @throws Exception
	 */
	public FastDfsHelper(String client_config, FastDFSTemplateFactory fdfsFactoryTemp) throws Exception {
		// String classPath = new
		// File(CommonConfig.class.getResource("/").getFile()).getCanonicalPath();
		ClassLoader classLoader = getClass().getClassLoader();
		InputStream resourceAsStream = classLoader.getResourceAsStream(client_config);
		//System.out.println("FastInito:" + fdfsClientConfigFilePath);
		ClientGlobal.init(resourceAsStream);
		fdfsFactoryTemp.setG_tracker_group(ClientGlobal.getG_tracker_group());
		this.setClient_config(client_config);
	}

	/**
	 * 获取一个连接
	 * 
	 * @return
	 * @throws Exception
	 */
	private StorageClient getClient() throws Exception {
		return factory.getClient();
	}

	/**
	 * 获取一个连接,用完自动关闭
	 * 
	 * @return
	 * @throws Exception
	 */
	public <T> T RunStorageClientClient(Function<T, StorageClient> func) throws Exception {
		StorageClient client = factory.getClient();
		T t = func.callback(client);
		// 回收资源
		factory.releaseConnection(client);
		return t;
	}

	/**
	 * 回收这个连接以便下次可以重用
	 * 
	 * @param client
	 */
	public void releaseConnection(StorageClient client) {
		factory.releaseConnection(client);
	}

	/**
	 * 文件上传
	 * 
	 * @param local_filename
	 *            文件路径
	 * @param file_ext_name
	 *            文件扩展名
	 * @param nvp
	 *            自定义数据信息
	 * @return
	 * @throws Exception
	 */
	public String[] fileUpLoad(String local_filename, String file_ext_name, NameValuePair nvp[]) throws Exception {
		StorageClient storageClient = getClient();
		String fileIds[] = storageClient.upload_file(local_filename, file_ext_name, nvp);
		System.out.println(fileIds.length);
		System.out.println("组名：" + fileIds[0]);
		System.out.println("路径: " + fileIds[1]);
		// 用完标记释放连接，提高资源利用率
		releaseConnection(storageClient);
		return fileIds;
	}

	public String[] fileUpLoad(byte[] bytes, String file_ext_name, NameValuePair nvp[]) throws Exception {
		// TODO Auto-generated method stub
		StorageClient storageClient = getClient();
		String fileIds[] = storageClient.upload_file(bytes, file_ext_name, nvp);
		System.out.println(fileIds.length);
		System.out.println("组名：" + fileIds[0]);
		System.out.println("路径: " + fileIds[1]);
		// 用完标记释放连接，提高资源利用率
		releaseConnection(storageClient);
		return fileIds;
	}

	/**
	 * 文件下载（现在是同步直接把所有字节获取，以后考虑性能和稳定性 会采用异步 +缓冲区来解决）
	 * 
	 * @param group_name
	 * @param remote_filename
	 * @throws Exception
	 */
	public byte[] fileDownload(String group_name, String remote_filename) throws Exception {
		StorageClient storageClient = getClient();
		byte[] bytes = storageClient.download_file(group_name, remote_filename);
		// 用完标记释放连接，提高资源利用率
		releaseConnection(storageClient);
		return bytes;
	}

	/**
	 * 获取文件信息
	 * 
	 * @param group_name
	 *            组名
	 * @param remote_filename
	 *            文件远程路径
	 * @return
	 * @throws Exception
	 */
	public FileInfo GetFileInfo(String group_name, String remote_filename) throws Exception {
		StorageClient storageClient = getClient();
		FileInfo fi = storageClient.get_file_info(group_name, remote_filename);
		System.out.println(fi.getSourceIpAddr());
		System.out.println(fi.getFileSize());
		System.out.println(fi.getCreateTimestamp());
		System.out.println(fi.getCrc32());
		// 用完标记释放连接，提高资源利用率
		releaseConnection(storageClient);
		return fi;
	}

	/**
	 * 获取文件自定义数据信息
	 * 
	 * @param group_name
	 *            组名
	 * @param remote_filename
	 *            文件远程路径
	 * @return
	 * @throws Exception
	 */
	public NameValuePair[] GetFileMate(String group_name, String remote_filename) throws Exception {
		StorageClient storageClient = getClient();
		NameValuePair nvps[] = storageClient.get_metadata(group_name, remote_filename);
		for (NameValuePair nvp : nvps) {
			System.out.println(nvp.getName() + ":" + nvp.getValue());
		}
		// 用完标记释放连接，提高资源利用率
		releaseConnection(storageClient);
		return nvps;
	}

	/**
	 * 文件删除
	 * 
	 * @param group_name
	 *            组名
	 * @param remote_filename
	 *            文件远程路径
	 * @return
	 * @throws Exception
	 */
	public boolean FileDelete(String group_name, String remote_filename) throws Exception {
		StorageClient storageClient = getClient();
		int i = storageClient.delete_file(group_name, remote_filename);
		System.out.println(i == 0 ? "删除成功" : "删除失败:" + i);
		// 用完标记释放连接，提高资源利用率
		releaseConnection(storageClient);
		return i == 0;
	}

	public String getClient_config() {
		return client_config;
	}

	private void setClient_config(String client_config) {
		this.client_config = client_config;
	}

}
